<?php
/**
 * Minhlog 后台用户功能控制器
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @category   Controller
 * @package    Backend
 * @copyright  Copyright (c) 2009-2010 Minh.Shu@gmail.com
 * @license    New BSD License
 * @author     Minh.Shu
 * @version    $Id: UserController.php 23 2010-02-16 09:03:56Z Minh.Shu $
 *
 */

class Backend_UserController extends Minh_Controller_Action
{
    public function init()
    {
        $this->_auth = new Minh_Auth_Db();
        parent::init();
    }

    public function loginAction ()
    {
        if (isset($_SESSION['Minhlog']['storage']->user_id)) {
            $this->_redirect('/backend/index/index/');
        }
        echo $this->view->render('login.phtml');
    }

    public function logincheckAction ()
    {
        //登陆验证
        $filter = new Zend_Filter_StripTags();
        $username = $filter->filter($this->_request->getPost('username'));
        $password = md5($filter->filter($this->_request->getPost('pwd')));

        if(empty($username) || empty($password)) $this->_redirect('/backend/index/index/');

        $authResult = $this->_auth->authUser($username, $password);
        if ($authResult->isValid()) {
            /**
             * @todo 验证持久化
             */
            $this->_auth->authPersist();

            $this->_redirect('/backend/index/index/');
        } else {
            /**
             * 登录失败记录错误信息和IP
             */
            $writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/logs/login_failure.txt', 'a');
            $format = '%ip% - [%timestamp%] : %message% *** %username% - %password% ***' .PHP_EOL ;
            $formatter = new Zend_Log_Formatter_Simple($format);
            $writer->setFormatter($formatter);

            $logger = new Zend_Log();
            $logger->setEventItem('ip', $this->getIP());
            $logger->setEventItem('username', $username);
            $logger->setEventItem('password', trim($this->_request->getPost('pwd')));
            $logger->addWriter($writer);
            $logger->info('登录失败.');

            switch ($authResult->getCode()) {
                case - 1:
                    echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /> <script type=\"text/javascript\" charset=\"utf-8\">alert(\"用户不存在!\");window.location.href=\"/backend/index/index/\";</script>";
                    break;
                case - 3:
                    echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /> <script type=\"text/javascript\" charset=\"utf-8\">alert(\"认证失败!\");window.location.href=\"/backend/index/index/\";</script>";
                    break;
            }
        }
    }

    public function logoutAction ()
    {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect('/backend/user/login/');
    }
}